<template>
  <div class="container">
    <Breadcrumb :items="['menu.teacher']" />
    <a-card class="general-card" :title="`教师管理`">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
            size="mini"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="nickname" :label="`教师姓名`">
                  <a-input
                    v-model="formModel.nickname"
                    :placeholder="`请输入教师姓名`"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="username" :label="`教师电话`">
                  <a-input
                    v-model="formModel.username"
                    :placeholder="`请输入教师电话`"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="title" :label="`班级名称`">
                  <a-input
                    v-model="formModel.title"
                    :placeholder="`请输入班级名称`"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="gender" :label="`性别`">
                  <a-select
                    v-model="formModel.gender"
                    :options="[
                      { label: '男', value: '1' },
                      { label: '女', value: '2' },
                    ]"
                    :placeholder="$t('searchTable.form.selectDefault')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="birthday" :label="`出生日期`">
                  <a-date-picker
                    v-model="formModel.birthday"
                    placeholder="出生日期"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="intr" :label="`任职`">
                  <a-input
                    v-model="formModel.intr"
                    :placeholder="`请输入任职`"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 74px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space :size="18" direction="vertical">
            <a-button type="primary" @click="search" size="small">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button @click="reset" size="small">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <!-- <a-divider style="margin-top: 0" /> -->
      <a-tabs v-model:activeKey="store.active" size="large" @change="search">
        <a-tab-pane
          :key="item.value"
          :title="`${item.label}(${item.count})`"
          v-for="item in store.options.audits"
        />
      </a-tabs>
      <a-modal
        v-model:visible="store.import.status"
        title="批量导入教师"
        draggable
        unmount-on-close
        :footer="false"
      >
        <a-steps
          changeable
          :current="store.import.current"
          @change="store.import.setCurrent"
        >
          <a-step description="请下载教师导入模板">下载模板</a-step>
          <a-step description="请在模板填写教师信息">填写教师信息</a-step>
          <a-step description="上传表格进行导入">确认导入</a-step>
        </a-steps>
        <div
          :style="{
            width: '100%',
            minHeight: '100px',
            margin: '20px 0',
            background: 'var(--color-bg-2)',
            color: '#C2C7CC',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }"
        >
          <div v-if="store.import.current == 1">
            <a-link :href="store.import.template" icon>教师导入模板</a-link>
          </div>
          <div v-if="store.import.current == 2">
            <a-image :src="store.import.tips" width="100%"></a-image>
          </div>
          <a-upload
            v-if="store.import.current == 3"
            draggable
            action="#"
            :auto-upload="false"
            :limit="1"
            @change="store.import.import"
            style="width: 100%"
            accept=".xlsx"
          />
        </div>
        <div
          style="display: flex; align-items: center; justify-content: center"
        >
          <a-space size="small">
            <a-button
              type="secondary"
              :disabled="store.import.current <= 1"
              @click="store.import.onPrev"
              size="small"
            >
              <IconLeft /> 上一步
            </a-button>
            <a-button
              type="primary"
              v-if="store.import.current != 3"
              @click="store.import.onNext"
              size="small"
            >
              下一步 <IconRight />
            </a-button>
            <a-button
              type="primary"
              v-else
              @click="store.import.cm"
              size="small"
            >
              确认导入
              <icon-import />
            </a-button>
          </a-space>
        </div>
      </a-modal>
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="store.add">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
            <!-- <a-upload @change="store.import">
              <template #upload-button>
                <a-button>
                  {{ $t('searchTable.operation.import') }}
                </a-button>
              </template>
            </a-upload> -->
            <a-button @click="store.import.click">
              {{ $t('searchTable.operation.import') }}
            </a-button>
            <a-button type="primary" status="danger" @click="store.dels">
              <template #icon>
                <icon-Delete />
              </template>
              批量删除
            </a-button>

            <a-button
              type="primary"
              status="success"
              @click="store.allAudits(3)"
              v-if="store.active == 2"
            >
              <template #icon>
                <icon-check-circle />
              </template>
              批量通过
            </a-button>
            <a-button
              type="primary"
              status="warning"
              @click="store.allAudits(3)"
              v-if="store.active == 2"
            >
              <template #icon>
                <icon-exclamation-circle />
              </template>
              批量驳回
            </a-button>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-button>
            <template #icon>
              <icon-download />
            </template>
            {{ $t('searchTable.operation.download') }}
          </a-button>
          <a-tooltip :content="$t('searchTable.actions.refresh')">
            <div class="action-icon" @click="search"
              ><icon-refresh size="18"
            /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('searchTable.actions.density')">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip :content="$t('searchTable.actions.columnSetting')">
            <a-popover
              trigger="click"
              position="bl"
              @popup-visible-change="popupVisibleChange"
            >
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div
                    v-for="(item, index) in showColumns"
                    :key="item.dataIndex"
                    class="setting"
                  >
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox
                        v-model="item.checked"
                        @change="
                          handleChange($event, item as TableColumnData, index)
                        "
                      >
                      </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :bordered="false"
        :size="size"
        page-position="bottom"
        @page-change="onPageChange"
        v-model:selectedKeys="store.selectedKeys"
        :row-selection="store.rowSelection"
        stripe
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <!-- <template #operations>
          <a-button v-permission="['admin']" type="text" size="small">
            {{ $t('searchTable.columns.operations.view') }}
          </a-button>
        </template> -->
        <template #gender="{ record }">
          {{ { 1: '男', 2: '女' }[record.gender] }}
        </template>
        <template #avatar="{ record }">
          <a-image width="60" height="60" :src="record.avatar" />
        </template>
        <template #id="{ record }">
          <a-space :size="18">
            <a-button type="outline" size="small" @click="store.edit(record)">
              <template #icon>
                <icon-Edit />
              </template>
              编辑
            </a-button>

            <a-popconfirm
              content="是否确认删除?"
              type="error"
              @ok="store.del(record.id)"
            >
              <a-button type="outline" size="small" status="danger">
                <template #icon>
                  <icon-Delete />
                </template>
                删除
              </a-button>
            </a-popconfirm>
            <a-popconfirm
              content="是否确认通过?"
              type="warning"
              @ok="store.audits(record.id, 3)"
              v-if="store.active == 2"
            >
              <a-button type="outline" status="success">
                <template #icon>
                  <icon-check-circle />
                </template>
                通过
              </a-button>
            </a-popconfirm>
            <a-popconfirm
              content="是否确认驳回?"
              type="warning"
              @ok="store.audits(record.id, 4)"
              v-if="store.active == 2"
            >
              <a-button type="outline" status="warning">
                <template #icon>
                  <icon-exclamation-circle />
                </template>
                驳回
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
      <a-modal
        v-model:visible="store.status"
        :title="`${store.form?.id ? '编辑教师' : '新建教师'}`"
        draggable
        unmount-on-close
        @before-ok="store.handleBeforeOk"
        @close="$refs.formRef.resetFields()"
        @open="store.open(focusRef, formRef)"
      >
        <a-form ref="formRef" :model="store.form" :rules="store.rules">
          <a-form-item field="username" label="手机号">
            <a-input
              ref="focusRef"
              v-model="store.form.username"
              placeholder="请输入手机号"
            />
          </a-form-item>
          <a-form-item field="password" label="密码">
            <a-input-password
              v-model="store.form.password"
              placeholder="请输入密码"
            />
          </a-form-item>
          <a-form-item field="squad_id" :label="`班级`">
            <a-select
              v-model="store.form.squad_id"
              :options="store.options.squad"
              :placeholder="`请选择班级`"
            />
          </a-form-item>
          <a-form-item field="intr" label="任职">
            <a-input v-model="store.form.intr" placeholder="请输入任职" />
          </a-form-item>
          <a-form-item field="nickname" label="姓名">
            <a-input v-model="store.form.nickname" placeholder="请输入姓名" />
          </a-form-item>
          <a-form-item field="gender" label="性别">
            <a-radio-group
              v-model="store.form.gender"
              :options="[
                { label: '男', value: '1' },
                { label: '女', value: '2' },
              ]"
            >
            </a-radio-group>
          </a-form-item>
          <a-form-item field="avatar" label="照片" validate-trigger="blur">
            <Upload v-model="store.form.avatar" :limit="1" />
          </a-form-item>
          <a-form-item field="birthday" label="出生日期">
            <a-date-picker
              v-model="store.form.birthday"
              placeholder="请选择出生日期"
              style="width: 100%"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick, onMounted } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import { Pagination } from '@/types/global';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';
  import Sortable from 'sortablejs';
  import { Divider, Message, Modal } from '@arco-design/web-vue';
  import { getData, Record, Params, savetData, delData } from './api';
  import { useTeacherStore } from '@/store/index';
  const store = useTeacherStore();
  const formRef = ref();
  const focusRef = ref();

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const generateFormModel = () => {
    return {
      nickname: ``,
      username: ``,
      birthday: ``,
      gender: ``,
      title: ``,
      intr: ``,
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref([]);
  const formModel = ref(generateFormModel());
  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);

  const size = ref<SizeProps>('small');

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
  };
  const pagination = reactive({
    ...basePagination,
    showTotal: true,
    showJumper: true,
    showPageSize: true,
    size: 'mini',
  });
  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);
  const columns = computed<TableColumnData[]>(() => [
    {
      title: t('searchTable.columns.index'),
      dataIndex: 'index',
      slotName: 'index',
      align: 'center',
    },
    {
      title: `姓名`,
      dataIndex: 'nickname',
      align: 'center',
    },
    {
      title: `电话`,
      dataIndex: 'username',
      align: 'center',
    },
    {
      title: `班级`,
      dataIndex: 'title',
      align: 'center',
    },
    {
      title: `年龄`,
      dataIndex: 'age',
      align: 'center',
    },
    {
      title: `性别`,
      dataIndex: 'gender',
      slotName: 'gender',
      align: 'center',
    },
    {
      title: `任职`,
      dataIndex: 'intr',
      align: 'center',
    },
    {
      title: `照片`,
      dataIndex: 'avatar',
      slotName: 'avatar',
      align: 'center',
    },
    {
      title: `操作`,
      dataIndex: 'id',
      slotName: 'id',
      align: 'center',
    },
  ]);

  const fetchData = async (params = { current: 1, pageSize: 10 }) => {
    setLoading(true);
    try {
      const { data } = await getData(params);
      console.log(data);
      store.options.audits[0].count = data.resolveTotal;
      store.options.audits[1].count = data.pendingTotal;
      store.options.audits[2].count = data.rejectTotal;
      store.import.template = data.template;
      store.import.tips = data.tips;
      renderData.value = data.list;
      store.options.squad = data.squad;
      pagination.current = params.current;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
      audits: store.active,
    } as unknown);
  };
  store.fetchData = search;

  const onPageChange = (current: number) => {
    fetchData({ ...basePagination, current });
  };

  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
  };

  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
  ) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
      );
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };

  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 先替换后面的，然后拿到替换的结果替换前面的
      newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
      );
    }
    return newArray;
  };

  const popupVisibleChange = (val: boolean) => {
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            exchangeArray(cloneColumns.value, oldIndex, newIndex);
            exchangeArray(showColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );
</script>

<script lang="ts">
  export default {
    name: 'GoodsType',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
